package com.ali.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 自定义过滤器
 */
@Slf4j
@Component
public class MyGatewayFilterFactory extends AbstractGatewayFilterFactory<MyGatewayFilterFactory.Config> {
    public static final String KEY = "type";

    public MyGatewayFilterFactory() {
        super(Config.class);
    }

    /**
     * 过滤规则
     */
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String type = exchange.getRequest().getQueryParams().getFirst(KEY);
            log.info("进入自定义过滤器，过滤器type：" + config.getType() + "，传值type:" + type);
            if (Objects.equals(config.getType(), type)) {
                return chain.filter(exchange);
            } else {
                throw new RuntimeException("自定义过滤器校验不通过");
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(KEY);
    }

    @Data
    public static class Config {
        private String type;
    }
}
